package com.cwt_taxi_xa;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.data.DataUtil;
import com.cwt_taxi_xa.data.SijiInfo;
import com.cwt_taxi_xa.db.bll.CarCallSystemBiz;
import com.cwt_taxi_xa.protocol.CardUtil;
import com.cwt_taxi_xa.protocol.MeterDecoder;
import com.cwt_taxi_xa.protocol.MeterEncoder;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.FileOper;
import com.cwt_taxi_xa.util.GPIOUtil;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.Tools;
import com.cwt_taxi_xa.util.VersionBiz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ActivityWaitQD extends CWTBaseActivity {

	final static String TAG = "ActivityWaitQD";
	public static boolean isview = false;

	public static boolean firstTime = true;

	ProgressDialog pd;
	ProgressDialog pd_sign;

	boolean shuaka = false;
	boolean jjqkj = false;
	public static boolean face = false;

	long time_tip = 0;
	long lastshuaka = 0;

	// 状态栏的时间和状态标志
	TextView tv_time;
	ImageView iv_online, iv_center, iv_gps;

	int shuakacount = 0;


	//后面改无卡签到新增
	ImageView iv_pc1,iv_pc2,iv_pc3;
	ImageView iv_del1,iv_del2,iv_del3;
	TextView tv_name1,tv_name2,tv_name3, tv_tip;
	EditText et_sfz;
	Button bt_sign, bt_shuaka;
	LinearLayout ly_siji, ly_tip;

	//后面改兼容西安卡标准
	LinearLayout ly_cardinfo;
	ListView lv_info;
	ImageView iv_cardpc;
	TextView tv_carname;
	Button bt_daoru;
	String[] ss_info1, ss_info2;
	String carpc_path;
	public static boolean daoru = false;

	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1001) {// 接收到签到刷卡信息
//				if (pd != null) {
//					pd.dismiss();
//				}
				if(!jjqkj){

//					if(SPUtils.getParamBoolean(SPConstants.SPK_faceSN, SPConstants.SPV_faceSN)){
//						TTsFunction.speakText("刷卡成功，请看摄像头完成人证对比");
//						startActivity(new Intent(ActivityWaitQD.this, ActivityCamera.class));
//					}else{
//						face = true;
//						tv2.setVisibility(View.GONE);
//						if(SPUtils.getParamInteger(SPConstants.SPK_jjq, SPConstants.SPV_jjq)==1){
//						TTsFunction.speakText("验证成功，请按IC键两秒打开计价器");
//							tv1.setText(Html.fromHtml("请按下计价器IC键<b><font color=#a6ff6f>"
//									+ " 2 " + "</b>秒"));
//						}else{
//						TTsFunction.speakText("验证成功，请按单程键三秒打开计价器");
//							tv1.setText(Html.fromHtml("请按下计价器单程键<b><font color=#a6ff6f>"
//									+ " 3 " + "</b>秒"));
//						}
//					}









//					tv2.setVisibility(View.GONE);
//					if(SPUtils.getParamInteger(SPConstants.SPK_jjq, SPConstants.SPV_jjq)==1){
//						TTsFunction.speakText("刷卡成功，请按IC键两秒打开计价器");
//						tv1.setText(Html.fromHtml("请按下计价器IC键<b><font color=#a6ff6f>"
//								+ " 2 " + "</b>秒"));
//					}else{
//						TTsFunction.speakText("刷卡成功，请按单程键三秒打开计价器");
//						tv1.setText(Html.fromHtml("请按下计价器单程键<b><font color=#a6ff6f>"
//								+ " 3 " + "</b>秒"));
//					}


				}
				steps();
			}else if (msg.what == 1002) {
				if(Constants.sijiNow&&Constants.sijiinfo!=null){
					shuakacount = 0;
					shuaka = true;
					if(!(MainApplication.topActivity instanceof ActivityCamera)){
						if(!face){
							if(System.currentTimeMillis()-lastshuaka>5*1000){
								lastshuaka = System.currentTimeMillis();
								handler.sendEmptyMessageDelayed(1001, 10);
							}
						}
					}
				}else{
					if(shuakacount>10){
						if(MyStatus.online&&MyStatus.center){
							Toast.makeText(ActivityWaitQD.this, "正在验证司机信息", 600).show();
							handler.sendEmptyMessageDelayed(1002, 500);
						}else{
							Toast.makeText(ActivityWaitQD.this, "网络异常", 600).show();
						}
					}else{
						Toast.makeText(ActivityWaitQD.this, "正在验证司机信息", 600).show();
						handler.sendEmptyMessageDelayed(1002, 500);
						shuakacount++;
					}
				}
			} else if (msg.what == 1003) {
				tv_time.setText((String) msg.obj);
			} else if (msg.what == 1004) {
				SerialPortService.getInstance()
						.sendSerialData6(
								MeterEncoder.sendDriverInfoForPower905("00E0",
										"11111",
										"22222",
//								DataUtil.getCompanyCode(),
//								DataUtil.getDriverCode(),
										SPUtils.getParamString(SPConstants.SPK_carcode, SPConstants.SPV_carcode),
										DateUtil.getNowDateToMeter(), 1,
										"0000000000", "0000", "90"));
//				if(shuaka&&face){
//					jjqkj = true;
//					steps();
//				}else{
//					if(System.currentTimeMillis()-time_tip>50*1000){
//						TTsFunction.speakText("抱歉，在人脸认证之前不能打开计价器，现在需要等待计价器自动恢复状态，请在一分钟后按正常流程刷卡认证后再打开计价器。");
//						time_tip = System.currentTimeMillis();
//					}
////					TTsFunction.speakText("计价器申请开机，请刷司机卡");
////					tv2.setVisibility(View.GONE);
////					tv1.setText("请刷司机卡");
//				}
			} else if (msg.what == 1005) {
				//默认刷卡签到

				SPUtils.setParam(SPConstants.SPK_signin, true);
				SPUtils.setParam(SPConstants.SPK_signinNum, Constants.sijiinfo.getSijicode());
				TTsFunction.speakText("签到成功");

				//签到成功后查询数据，用于后面直接签退（开机直接签到的自检界面会去查）---------------------------------------------
				//签到成功后查询数据，用于后面直接签退（开机直接签到的自检界面会去查）---------------------------------------------
				//签到成功后查询数据，用于后面直接签退（开机直接签到的自检界面会去查）---------------------------------------------
				//签到成功后查询数据，用于后面直接签退（开机直接签到的自检界面会去查）---------------------------------------------
				SerialPortService.getInstance().sendSerialData6(MeterEncoder.queryMeterState());


				startActivity(new Intent(ActivityWaitQD.this,
						ActivityMain.class));
				finish();
			} else if (msg.what == 1006) {
				TTsFunction.speakText("异常，强制签退");
				SerialPortService.getInstance().sendSerialData6(
						MeterEncoder.sendDriverInfoForPower905("00E3",
								DataUtil.getCompanyCode(),
								DataUtil.getDriverCode(),
								SPUtils
										.getParamString(SPConstants.SPK_carcode,
												SPConstants.SPV_carcode), DateUtil
										.getNowDateToMeter(), 1, "0000000000", "0000",
								"90"));
				startActivity(new Intent(ActivityWaitQD.this,
						ActivityMain.class));
				finish();
			} else if (msg.what == 1007) {
				// 刷新右上角状态位-网络
				iv_online
						.setImageResource((Boolean) msg.obj ? R.drawable.cwtic_bs1_on
								: R.drawable.cwtic_bs1_off);
			} else if (msg.what == 1008) {
				// 刷新右上角状态位-平台
				iv_center
						.setImageResource((Boolean) msg.obj ? R.drawable.cwtic_bs2_on
								: R.drawable.cwtic_bs2_off);
			} else if (msg.what == 1009) {
				// 刷新右上角状态位-定位
				iv_gps
						.setImageResource((Boolean) msg.obj ? R.drawable.cwtic_bs3_on
								: R.drawable.cwtic_bs3_off);
			}
			else if(msg.what==1010){
				//当前未签到界面，收到计价器已开机心跳，同步状态
				TTsFunction.speakText("同步计价器状态");
				SPUtils.setParam(SPConstants.SPK_signin, true);
				startActivity(new Intent(ActivityWaitQD.this, ActivityMain.class));
				finish();
			}

			/**
			 * 开机自检报告
			 */
			else if(msg.what==1011){
				ActivityPower.sleep = true;
				startActivity(new Intent(ActivityWaitQD.this, ActivityPower.class));
			}


			/**
			 * 获取到司机照片
			 */
			else if(msg.what==1012){
				try {
					bt_sign.setEnabled(true);
					pd_sign.dismiss();
					pd_sign = null;
				} catch (Exception e) {
					// TODO: handle exception
				}
				Intent intent = new Intent(ActivityWaitQD.this, ActivityCamera.class);
				try {

					startActivityForResult(intent, 1);
//					startActivity(intent);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else if(msg.what==1013){
				try {
					bt_sign.setEnabled(true);
					pd_sign.dismiss();
					pd_sign = null;
				} catch (Exception e) {
					// TODO: handle exception
				}
				Toast.makeText(ActivityWaitQD.this, "获取司机信息出错", 1000).show();
			}

			else if(msg.what==1014){
				try {
					bt_sign.setEnabled(true);
					if(pd_sign!=null)
						pd_sign.dismiss();
					pd_sign = null;
				} catch (Exception e) {
					// TODO: handle exception
				}
				ActivityWaitQD.face = true;
				if(DataUtil.getJJQ()==1){
					//TTsFunction.speakText("验证成功，请按IC键两秒打开计价器");
				}else if(DataUtil.getJJQ()==2){
					TTsFunction.speakText("验证成功，请按单程键3秒打开计价器");
				}else if(DataUtil.getJJQ()==3){
					TTsFunction.speakText("验证成功，请按暂停键两秒后松开");
					//DecoderSZ55aa.decoderData("计价器", bytes , ActivityWaitQD.this);
					//SerialPortService.getInstance().sendSerialData6(EncoderSZ55aa.getMeterDtuBody("00F2", Tools.parseHexStr2Byte("90")));

				}

				AppLog.d("ltj ---------------------------1014 ActivityWaitQD.face = true");
				savesijibiaoshi();
				initList();

				//SerialPortService.getInstance().sendSerialData6(MeterEncoder.getMeterDtuBody("00E0",new byte[]{(byte) 0x90}));
				//SerialPortService.getInstance().sendSerialData6(MeterEncoder.getMeterDtuBody("00E0",Tools.parseHexStr2Byte("90")));

				MeterDecoder.processMeter("00E0", Tools.parseHexStr2Byte("90"), ActivityWaitQD.this);
			}

			else if(msg.what==1016){
				String str = (String) msg.obj;
				if(!face&&pd_sign==null){
					signinfo(str, true);
				}
			}

			else if(msg.what==1017){
//				ly_cardinfo.setVisibility(View.VISIBLE);
				ss_info1 = (String[]) msg.obj;
//				tv_carname.setText(ss_info1[4]);
//				String[] ss = new String[ss_info1.length];
//				for (int i = 0; i < ss_info1.length; i++) {
//					ss[i] = ((i+1)+" : ")+ss_info1[i];
//				}
//				ArrayAdapter<String> ad = new ArrayAdapter<>(ActivityWaitQD.this, android.R.layout.simple_list_item_1, ss);
//				lv_info.setAdapter(ad);

				Toast.makeText(ActivityWaitQD.this, "开始读取照片，请不要移动卡片", 2000).show();

				Intent intent = new Intent(ActivityWaitQD.this, ActivityCardInfo.class);
				intent.putExtra("ss_info1", ss_info1);
				startActivityForResult(intent, 2);
			}
			else if(msg.what==1020){
				//新增ic卡对比
				String sijic = (String) msg.obj;
				bt_sign.setEnabled(false);
				signinfo(sijic, true);
				//设置IC卡签到
				setCheckInCertificate();
			}

			else if(msg.what==1066){
				if(daoru){
					daoru = false;
					TTsFunction.speakText("卡信息成功导入本地");
					initList();
				}
			}

//			else if(msg.what==1018){
//				carpc_path = (String) msg.obj;
//				AppLog.e(carpc_path);
//				Bitmap bm = ActivityCamera.getLoacalBitmap(carpc_path);
//				if(bm!=null) iv_cardpc.setImageBitmap(bm);
//			}
//
//			else if(msg.what==1019){
//				ss_info2 = (String[]) msg.obj;
//				String[] ss = new String[ss_info1.length+ss_info2.length];
//				System.arraycopy(ss_info1, 0, ss, 0, ss_info1.length);
//				System.arraycopy(ss_info2, 0, ss, ss_info1.length, ss_info2.length);
//
//				saveCardInfo(ss);
//
//				String[] ss2 = new String[ss.length];//不新建空间会导致后面的处理和前面的保存冲突
//				for (int i = 0; i < ss.length; i++) {
//					ss2[i] = ((i+1)+" : [")+CardUtil.infoKeys[i]+"] "+ss[i];
//				}
//				ArrayAdapter<String> ad = new ArrayAdapter<>(ActivityWaitQD.this, android.R.layout.simple_list_item_1, ss2);
//				lv_info.setAdapter(ad);
//
//			}

		};
	};

	TextView tv1, tv2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.openSwipeBack(false);
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_aa_waitqd2);

//		findViewById(R.id.textView4).setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(ActivityWaitQD.this, ActivityJJQ.class));
//			}
//		});



		//默认调亮屏幕
		CarCallSystemBiz.saveScreenBrightness(ActivityWaitQD.this, 250);


		//服务评价器使能
		//右侧灯板
		GPIOUtil.writeToDevice(1, "/proc/panel_backlight");
		//左侧灯板
//		GPIOUtil.writeToDevice(1, "/proc/rfid_pow_switch");
//		GPIOUtil.writeToDevice(1, "/proc/red_switch");
//		GPIOUtil.writeToDevice(1, "/proc/green_switch");
//		GPIOUtil.writeToDevice(1, "/proc/yellow_switch");
//		GPIOUtil.writeToDevice(1, "/proc/blue_switch");

		// 打开功放
		GPIOUtil.writeToDevice(1, "/proc/amp_switch");

		//测试tvin悬浮窗
//		startService(new Intent(ActivityWaitQD.this, FloatService.class));

		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// for (int i = 0; i < 60*60; i++) {
		// try {
		// Thread.sleep(1000);
		// //
		// CarCallApplication.getInstance().sendSerialData6("asdfdasfdasf".getBytes());
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		// }
		// }
		// }).start();


		if (SPUtils.getParamBoolean(SPConstants.SPK_signin,
				SPConstants.SPV_signin)) {
			AppLog.e("------------------1000");
			startActivity(new Intent(ActivityWaitQD.this, ActivityMain.class));

		} else {
			AppLog.e("------------------10002");
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						Thread.sleep(800);//800
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// TODO Auto-generated method stub
					CardUtil.mCardManager.changeCheckInState();
					//签到后关闭射频
				}
			}).start();

//			TTsFunction.speakText("       欢迎");
		}

		tv_time = (TextView) findViewById(R.id.textView1);

		iv_online = (ImageView) findViewById(R.id.imageView8);
		iv_center = (ImageView) findViewById(R.id.imageView9);
		iv_gps = (ImageView) findViewById(R.id.imageView10);



		et_sfz = (EditText) findViewById(R.id.et_shenfenzheng);
		bt_sign = (Button) findViewById(R.id.bt_qiandao);
		bt_shuaka = (Button) findViewById(R.id.bt_shuaka);
		iv_pc1 = (ImageView) findViewById(R.id.iv_pc1);
		iv_pc2 = (ImageView) findViewById(R.id.iv_pc2);
		iv_pc3 = (ImageView) findViewById(R.id.iv_pc3);
		iv_del1 = (ImageView) findViewById(R.id.iv_del1);
		iv_del2 = (ImageView) findViewById(R.id.iv_del2);
		iv_del3 = (ImageView) findViewById(R.id.iv_del3);
		tv_name1 = (TextView) findViewById(R.id.tv_name1);
		tv_name2 = (TextView) findViewById(R.id.tv_name2);
		tv_name3 = (TextView) findViewById(R.id.tv_name3);
		ly_siji = (LinearLayout) findViewById(R.id.ly_sijiinfo);
		ly_tip = (LinearLayout) findViewById(R.id.ly_tip);
		tv_tip = (TextView) findViewById(R.id.tv_tip);

		ly_cardinfo = (LinearLayout) findViewById(R.id.ly_cardinfo);
		lv_info = (ListView) findViewById(R.id.listView1);
		iv_cardpc = (ImageView) findViewById(R.id.imageView1);
		tv_carname = (TextView) findViewById(R.id.textView2);
		bt_daoru = (Button) findViewById(R.id.bt_daoru);
		//setSfz();
		bt_daoru.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ly_cardinfo.setVisibility(View.GONE);
				if(daoru){
					daoru = false;
					TTsFunction.speakText("卡信息成功导入本地");
					initList();
				}
			}
		});

//		bt_sign.setEnabled(false);
//		et_sfz.setText("过渡版本，直接按计价器开机");
//		et_sfz.setEnabled(false);

//		et_sfz.setText("610428197601281615");


		bt_sign.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
//				Intent intent = new Intent(ActivityWaitQD.this, ActivityCamera.class);
//				try {
//					intent.putExtra("pic", FileUtil.readFileByBytes("/mnt/sdcard/司机照片.jpg"));
//					startActivity(intent);
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}

				String str = et_sfz.getText().toString();
				str = str.replaceAll(" ", "");
				et_sfz.setText("");
				//setSfz();
				//拿到InputMethodManager
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				//如果window上view获取焦点 && view不为空
				if(imm.isActive()&&getCurrentFocus()!=null){
					//拿到view的token 不为空
					if (getCurrentFocus().getWindowToken()!=null) {
						//表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
						imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
					}
				}

				String time = new SimpleDateFormat("HHddMMyy").format(new Date());


				//特殊情况处理
				if(str.equals("888888")){
					Constants.sijiinfo = new SijiInfo();
					Constants.sijiinfo.setSijicode("12345");
					Constants.sijiinfo.setQiyecode("12345");
					face = true;
					AppLog.d("ltj ---------------------------请按计价器签到 ActivityWaitQD.face = true");
					et_sfz.setText("特殊处理，请按计价器签到");
					setCheckInFace();
					return;
				}

				//特殊情况处理
				if(str.equals("刷卡测试")){
					SPUtils.setParam(SPConstants.SPK_ScardExist, true);
					return;
				}
				//特殊情况处理
				if(str.equals("关闭刷卡测试")){
					SPUtils.setParam(SPConstants.SPK_ScardExist, false);
					return;
				}


				if(str.equals(time)){
					startActivity(new Intent(ActivityWaitQD.this, ActivityJJQ.class));
					return;
				}

				if(str.equals(time+time+time)){
					SPUtils.setParam(SPConstants.SPK_signin, true);
					startActivity(new Intent(ActivityWaitQD.this, ActivityMain.class));
				}

				if(str.contains("删除")){
					str = str.replaceAll("删除", "");
					if(str.length()>0){
						File f = new File(Constants.SDPath+str);
						if(f.exists()){
							if(deleteFile(f)){
								Toast.makeText(ActivityWaitQD.this, "删除成功", 1000).show();
							}else{
								Toast.makeText(ActivityWaitQD.this, "删除失败", 1000).show();
							}
						}else{
							Toast.makeText(ActivityWaitQD.this, "文件不存在", 1000).show();
						}
					}else{
						Toast.makeText(ActivityWaitQD.this, "输入有误", 1000).show();
					}
					return;
				}





				if(str.length()>0){
					bt_sign.setEnabled(false);
					signinfo(str, true);
				}




			}
		});




		bt_shuaka.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//签到后关闭射频
				CardUtil.mCardManager.changeCheckInState();
				CardUtil.mCardManager.startAndRead();
			}
		});




//		tv1 = (TextView) findViewById(R.id.textView2);
//		tv2 = (TextView) findViewById(R.id.textView3);
//		// 测试----------------------------------------------------------
//		tv1.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				// CarCallApplication.sendSerialData6(EncoderSZ55aa.getMeterDtuBody("0000",
//				// Tools.str2Bcd(DateUtil.getTodayDate(DateUtil.df8))));
//
//				// startActivity(new Intent(ActivityWaitQD.this,
//				// ActivityMain.class));
////				SerialPortService.getInstance().sendSerialData2(
////						"asdfasdfasdfsdf".getBytes());
//
//				//模拟刷卡签退  卡类型-企业号-司机号-车牌
////				String[] info = {"1","1110","123123","B12345"};
////				handler.sendMessage(handler.obtainMessage(1002, info));
//
////				SerialPortService.getInstance().sendSerialData2(Tools.parseHexStr2Byte("55AA0004000021012455AA"));
//
//
////				 startActivity(new Intent(ActivityWaitQD.this,
////				 ActivityWriteCard.class));
//
////				startActivity(new Intent(ActivityWaitQD.this, VideoActivity.class));
//
//
////				HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList();
////				AppLog.e("--------------------"+deviceHashMap.size());
////				AppLog.e("--------------------"+deviceHashMap.entrySet().size());
////				for (Entry<String, UsbDevice> entry : deviceHashMap.entrySet()) {
////					Log.e("---------", "detectUsbDeviceWithUsbManager: " + entry.getKey() + ", " + entry.getValue());
////				}
//			}
//		});

		/**
		 * 检测IO口
		 */
		// new Thread(new Runnable() {
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// String[] ss = {"/proc/amp_switch", "/proc/input1", "/proc/input2",
		// "/proc/input3", "/proc/input5", "/proc/input6"};
		// for (int i = 0; i < 60 * 60; i++) {
		// try {
		// Thread.sleep(5000);
		// for (int j = 0; j < ss.length; j++) {
		// getGPIO(ss[j]);
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		//
		// }
		// }).start();

		// Button bt1 = (Button) findViewById(R.id.button1);
		// bt1.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		// // CardUtil.setCardData(1,
		// // Tools.parseHexStr2Byte("01020304050607080910111213141516"));
		//
		// startActivity(new Intent(ActivityWaitQD.this, VideoActivity.class));
		//
		// // TTsFunction.speakText("语音测试 语音测试 语音测试");
		// }
		// });
		//
		// Button bt2 = (Button) findViewById(R.id.button2);
		// bt2.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		//
		// startActivity(new Intent(ActivityWaitQD.this, ActivityMain.class));
		// }
		// });
		//
		// Button bt3 = (Button) findViewById(R.id.button3);
		// bt3.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// String[] ss = {"/proc/amp_switch", "/proc/input1", "/proc/input2",
		// "/proc/input3", "/proc/input5", "/proc/input6"};
		// setGPIO("1", ss[0]);
		// // for (int i = 0; i < ss.length; i++) {
		// // setGPIO("1", ss[i]);
		// // }
		// }
		// });
		//
		// Button bt4 = (Button) findViewById(R.id.button4);
		// bt4.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// String[] ss = {"/proc/amp_switch", "/proc/input1", "/proc/input2",
		// "/proc/input3", "/proc/input5", "/proc/input6"};
		// setGPIO("0", ss[0]);
		// // for (int i = 0; i < ss.length; i++) {
		// // setGPIO("0", ss[i]);
		// // }
		// }
		// });

		//
		// if (Constants.splashScreen) {
		// Constants.splashScreen = false;
		// initData();
		// }

	}

	private void setSfz(){
		et_sfz.setText("610122197406093438");
	}


	public static boolean deleteFile(File dirFile) {
		if (!dirFile.exists()) {
			return false;
		}

		if (dirFile.isFile()) {
			return dirFile.delete();
		} else {

			for (File file : dirFile.listFiles()) {
				deleteFile(file);
			}
		}

		return dirFile.delete();
	}


	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);

		if(arg0==1&&arg1==123){
			handler.sendEmptyMessage(1014);
			setCheckInFace();
		}

		if(arg0==2&&arg1==456){
			handler.sendEmptyMessage(1066);
		}
	}



	private void savesijibiaoshi() {
		for (int i = 0; i < 3; i++) {
			String sjcode = SPUtils.getParamString("sijilocdata"+i, "");
			if(sjcode.length()<1){
				SPUtils.setParam("sijilocdata"+i, DataUtil.getlastCarNum());
				return;
			}
			if(sjcode.equals(DataUtil.getlastCarNum())) return;
		}
		String[] codes = new String[3];
		codes[0] = DataUtil.getlastCarNum();
		codes[1] = SPUtils.getParamString("sijilocdata0", "");;
		codes[2] = SPUtils.getParamString("sijilocdata1", "");;
		for (int i = 0; i < codes.length; i++) {
			SPUtils.setParam("sijilocdata"+i, codes[i]);
		}
	}


	public void steps() {
		if (shuaka && jjqkj) {
			SerialPortService.getInstance()
					.sendSerialData6(
							MeterEncoder.sendDriverInfoForPower905("00E0",
									DataUtil.getCompanyCode(),
									DataUtil.getDriverCode(),
									SPUtils.getParamString(SPConstants.SPK_carcode, SPConstants.SPV_carcode),
									DateUtil.getNowDateToMeter(), 1,
									"0000000000", "0000", "90"));
		}
//		Driver driver = DataUtil.getNowDriverInfor();
//		SerialPortService.getInstance()
//		.sendSerialData6(
//				MeterEncoder.sendDriverInfoForPower905("00E0",
//						"12345",
//						"12345",
//						SPUtils.getParamString(SPConstants.SPK_carcode, SPConstants.SPV_carcode),
//						DateUtil.getNowDateToMeter(), 1,
//						"0000000000", "0000", "90"));
	}

	public void setGPIO(String status, String path) {
		try {
			File f = new File(path);
			Writer w = new FileWriter(f);
			w.write(status);
			w.close();
			Log.e("设置GPIO", "IO口：" + path + "   写入：" + status);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getGPIO(String path) {
		String status = "-1";
		try {
			BufferedReader reader = new BufferedReader(new FileReader(path));
			status = reader.readLine();
			Log.e("检测IO口", path + " : " + status);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}





	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isview = true;


		if(firstTime){
			firstTime = false;
			handler.sendMessageDelayed(handler.obtainMessage(1011), 1500);
		}



//		 if(shuaka&&face){
//				tv2.setVisibility(View.GONE);
//				if(SPUtils.getParamInteger(SPConstants.SPK_jjq, SPConstants.SPV_jjq)==1){
//					TTsFunction.speakText("验证成功，请按IC键两秒打开计价器");
//					tv1.setText(Html.fromHtml("请按下计价器IC键<b><font color=#a6ff6f>"
//							+ " 2 " + "</b>秒"));
//				}else{
//					TTsFunction.speakText("验证成功，请按单程键三秒打开计价器");
//					tv1.setText(Html.fromHtml("请按下计价器单程键<b><font color=#a6ff6f>"
//							+ " 3 " + "</b>秒"));
//				}
//		 }


		if (SPUtils.getParamBoolean(SPConstants.SPK_signin,
				SPConstants.SPV_signin)) {
			AppLog.e("------------------1000");
			startActivity(new Intent(ActivityWaitQD.this, ActivityMain.class));
		}else{
			initList();
//			 et_sfz.setText("612525197709180873");
		}



	}

	/**
	 * 初始化本地司机数据
	 */
	public static SijiInfo[] sijiInfoList = new SijiInfo[3];
	private void initList() {
		initsijiData(0, iv_pc1, iv_del1, tv_name1);
		initsijiData(1, iv_pc2, iv_del2, tv_name2);
		initsijiData(2, iv_pc3, iv_del3, tv_name3);
		if(face){
			ly_siji.setVisibility(View.GONE);
			ly_tip.setVisibility(View.VISIBLE);
			if(DataUtil.getJJQ()==1){
				tv_tip.setText("验证成功，请按IC键两秒打开计价器");
			}else if(DataUtil.getJJQ()==2){
				tv_tip.setText("验证成功，请按单程键3秒打开计价器");
			}else if(DataUtil.getJJQ()==3){
				tv_tip.setText("验证成功，请按暂停键两秒后松开");
			}
		}else{
			ly_siji.setVisibility(View.VISIBLE);
			ly_tip.setVisibility(View.GONE);
		}
	}
	private void initsijiData(final int i, ImageView iv_pc, ImageView iv_del, TextView tv_name) {
		try {
			//sjcode是获取司机信息的标识，原来是外卡号，后面改成身份证号
			final String sjcode = SPUtils.getParamString("sijilocdata"+i, "");
			AppLog.d(TAG,"initsijiData sjcode:" + sjcode);
			if(sjcode.length()>0){
				sijiInfoList[i] = VersionBiz.getSijiInfo(sjcode);
				if(sijiInfoList[i] != null){
					iv_del.setVisibility(View.VISIBLE);
					iv_del.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							AlertDialog.Builder normalDialog = new AlertDialog.Builder(ActivityWaitQD.this);
							normalDialog.setTitle("提示");
							if(sijiInfoList[i]==null){
								normalDialog.setMessage("删除异常数据？");
							}else{
								normalDialog.setMessage("确定要删除"+sijiInfoList[i].getName()+"的本地数据吗？");
							}
							normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									String num = SPUtils.getParamString("sijilocdata"+i, "");
									if(Constants.sijiinfo != null){
										AppLog.d("ltj ---------------------------getSijicode:" + Constants.sijiinfo.getSijicode());
										if(Constants.sijiinfo.getSijicode().equals(num)){
											face = false;
										}
									}
									AppLog.d("ltj ---------------------------num:" + num);
									if(num.length()>0){
										FileOper.del(new File(Constants.SDPath+num));
										AppLog.d("ltj ---------------------------filepath:" + Constants.SDPath+num);
//										if(f.exists()){
//											if(f.delete()){
//												Toast.makeText(ActivityWaitQD.this, "删除成功", 1000).show();
//											}else{
//												Toast.makeText(ActivityWaitQD.this, "删除失败", 1000).show();
//											}
//										}else{
//											Toast.makeText(ActivityWaitQD.this, "文件不存在", 1000).show();
//										}

									}
									SPUtils.setParam("sijilocdata"+i, "");
									sijiInfoList[i] = null;
									initList();
								}
							});
							normalDialog.setNegativeButton("取消", null);
							normalDialog.show();
						}
					});
					//AppLog.d(TAG,"initsijiData sijiInfoList["+ i +"]:" + sijiInfoList[i]);
					Bitmap bm = ActivityCamera.getLoacalBitmap(sijiInfoList[i].getPhoto());
					if(bm!=null) iv_pc.setImageBitmap(bm);
					tv_name.setText(sijiInfoList[i].getName());
					iv_pc.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							if(sijiInfoList[i].getSigninTpye() == 1 && (!Constants.FACE_WITH_CARD_ENABLE)){
								TTsFunction.speakText("请使用IC从业资格证签到");
							}else if(MyStatus.online){
								//屏蔽人脸识别
								signinfo(sjcode, false);
							}else{
								TTsFunction.speakText("网络未连接，请手动输入身份证号签到");
								Toast.makeText(ActivityWaitQD.this, "网络未连接，请手动输入身份证号签到", 2000).show();
							}
						}
					});
				}else{
					TTsFunction.speakText("缓存数据解析错误,请手动删除数据后重试");//缓存数据解析错误,正删除缓存,请稍后再试
					AppLog.e(TAG,"sijiInfoList[i] " + sjcode + "缓存数据解析错误,请手动删除数据后重试!" );//缓存数据解析错误,正删除缓存,请稍后再试
					//删除数据很危险,切记
					//FileOper.del(new File(Constants.SDPath + sjcode));
				}

			}else{
				iv_del.setVisibility(View.GONE);
				iv_pc.setImageResource(R.drawable.sijiquesheng);
				tv_name.setText("");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	//通过标识先获取本地，没有再获取在线的
	public int signing = 0;
	protected void signinfo(String sjcode, boolean passface) {
		signing = 1;
		DataUtil.savelastCarNum(sjcode);
		if(pd_sign==null){
			pd_sign = ProgressDialog.show(ActivityWaitQD.this, "请稍等", "正在验证司机信息");
		}else{
			pd_sign.show();
		}



		Constants.sijiinfo = VersionBiz.getSijiInfo(sjcode);

//		AppLog.e("本地获取司机信息："+Constants.sijiinfo==null?"null":Constants.sijiinfo.getName());
		//异步
		if(Constants.sijiinfo==null){
			VersionBiz.doCheckSJInfor(sjcode, new checkSJinfor() {
				@Override
				public void onInfor(boolean result) {
					if(result){
						new Thread(new Runnable() {
							@Override
							public void run() {
								for (int i = 0; i < 5; i++) {
									try {
										Thread.sleep(1000);
										if(Constants.sijiinfo!=null&&Constants.sijiinfo.getPhoto()!=null){
											File f = new File(Constants.sijiinfo.getPhoto());
											if(f.exists()){
												handler.sendEmptyMessage(1012);
												break;
											}
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						}).start();
					}else{
						handler.sendEmptyMessage(1013);
					}
				}
			});
		}else{
			//本地已有数据的，passface成立，直接让签到
			if(passface){
				//handler.sendEmptyMessage(1014);
				if(checkSijiInfo(Constants.sijiinfo,CardUtil.sijiInfo)){
					if(Constants.FACE_AND_CARD_DISABLE){
						handler.sendEmptyMessage(1014);//启动IC
					}else{
						handler.sendEmptyMessage(1012);//启动人脸识别
					}
				}else if(Constants.sijiinfo!=null/*&&Constants.sijiinfo.getPhoto()!=null*/){
					//File f = new File(Constants.sijiinfo.getPhoto());
					//if(f.exists()){
						handler.sendEmptyMessage(1014);
					//}
				}else{
					//这里启动人脸识别码?
					handler.sendEmptyMessage(1013);
				}
			}else{
				handler.sendEmptyMessage(1012);//启动人脸识别
			}
		}


	}

	/**
	 * 读卡结束后保存卡信息到本地
	 * @param ss
	 */
	@Deprecated
	public void saveCardInfo(String[] ss){
		//保存sp卡号
		final String number = ss_info1[3];
		DataUtil.savelastCarNum(number);
		savesijibiaoshi();

		//保存照片
		final String path = Constants.SDPath+number+"/司机照片.jpg";
		new Thread(){
			public void run() {
				try {
					//打开输入流
					InputStream inputStream = new FileInputStream(carpc_path);

					File file = new File(Constants.SDPath+number);
					if(!file.exists()){
						file.mkdir();
					}

					file=new File(path);
					if(file.exists()) file.delete();
					FileOutputStream fileOutputStream=new FileOutputStream(file);
					int hasRead=0;
					while((hasRead=inputStream.read())!=-1){
						fileOutputStream.write(hasRead);
					}
					fileOutputStream.close();
					inputStream.close();

					daoru = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();

		//保存司机文本信息到本地
		Constants.sijiinfo = new SijiInfo();

		//姓名
		Constants.sijiinfo.setName(ss_info1[4]);

		//司机号
		Constants.sijiinfo.setSijicode(ss_info1[3]);

		//企业号
		Constants.sijiinfo.setQiyecode(ss_info2[12]);

		//资格证有效期
		Constants.sijiinfo.setCertificateData(ss_info2[2]);

		//照片
		Constants.sijiinfo.setPhoto(path);

		//星级1-5
		try {
			Constants.sijiinfo.setStar(Integer.parseInt(ss_info2[8]));
		} catch (Exception e) {
			Constants.sijiinfo.setStar(5);
		}

		//所属公司
		Constants.sijiinfo.setCompanyname(ss_info2[13]);

		//监督电话
		Constants.sijiinfo.setMobile(ss_info2[3]);

		//二维码
//		Constants.sijiinfo.setQrCode1(DLPIC(number, obj.getString("qrCode1"), "二维码1"));

		//二维码
//		Constants.sijiinfo.setQrCode2(DLPIC(number, obj.getString("qrCode2"), "二维码2"));

		//卡号
		Constants.sijiinfo.setCardnum("000000");

		Constants.sijiNow = true;

		//保存信息文本
		VersionBiz.saveSijiInfo(number, Constants.sijiinfo, ss);
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();


		isview = false;

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		AppLog.d(TAG, "onDestroy CardUtil.mCardManager.stop()");
		CardUtil.mCardManager.stop();
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub
		switch (index) {
			case 1:
				handler.sendMessage(handler.obtainMessage(1007, status));
				break;
			case 2:
				handler.sendMessage(handler.obtainMessage(1008, status));
				break;
			case 3:
				handler.sendMessage(handler.obtainMessage(1009, status));
				break;
			default:
				break;
		}
	}


	VersionBiz ver;
	@Override
	public void sendMsg(int type, Object obj) {
		if (type == 1001) {
			handler.sendMessage(handler.obtainMessage(1002));
		}

		if (type == 1002) {
			handler.sendMessage(handler.obtainMessage(1003, obj));
		}

		if (type == 1003) {
			handler.sendEmptyMessage(1004);
		}

		if (type == 1004) {
			handler.sendEmptyMessage(1005);
		}

		if (type == 1005) {
			handler.sendEmptyMessage(1006);
		}
		if (type == 1011){
			if((Boolean)obj){
				handler.sendMessage(handler.obtainMessage(1010));
			}
		}

		if (type == 1016){
			handler.sendMessage(handler.obtainMessage(1016, obj));
		}

		if (type == 10087){
			handler.sendMessage(handler.obtainMessage(1017, obj));
		}
		if (type == 10088){
			handler.sendMessageDelayed(handler.obtainMessage(1018, obj), 1000);
		}
		if (type == 10089){
			handler.sendMessageDelayed(handler.obtainMessage(1019, obj), 1000);
		}

		if (type == 10099){
			handler.sendMessage(handler.obtainMessage(1020, obj));
		}

	}

	public void setCheckInFace(){
		SPUtils.setParam(SPConstants.SPK_ScardExist, false);
		SPUtils.setParam(SPConstants.SPK_faceSN, true);
		CardUtil.mCardManager.stop();
	}

	public void setCheckInCertificate(){
		SPUtils.setParam(SPConstants.SPK_ScardExist, true);
		SPUtils.setParam(SPConstants.SPK_faceSN, false);
	}


	public void setRevertCheckIn(){
		SPUtils.setParam(SPConstants.SPK_ScardExist, false);
		SPUtils.setParam(SPConstants.SPK_faceSN, false);
	}

	public static boolean hasReadCard(String sijiCode){
		boolean result = false;
		if(getSiJiIndex(sijiCode)>-1){
			AppLog.d(TAG,"hasReadCard true");
			result = true;
		}
		return result;
	}


	//获取已保存司机数组索引
	public static int getSiJiIndex(String sijiCode){
		int index = -1;
		if(!TextUtils.isEmpty(sijiCode)){
			if(ActivityWaitQD.sijiInfoList!=null){
				for (int i = 0; i < ActivityWaitQD.sijiInfoList.length; i++) {
					if(ActivityWaitQD.sijiInfoList[i]!=null){
						if(sijiCode.equals(ActivityWaitQD.sijiInfoList[i].getSijicode())){
							index = i;
							break;
						}
					}
				}
			}
		}
		return index;
	}

	private boolean checkSijiInfo(SijiInfo info,SijiInfo sijiInfo){
		AppLog.i(TAG,"checkSijiInfo info:" + info);
		AppLog.i(TAG,"checkSijiInfo sijiInfo:" + sijiInfo);
		if(sijiInfo != null && info != null){

			try {
				if(sijiInfo.equals(info)){
					return true;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return false;
	}

	public interface checkSJinfor{
		public void onInfor(boolean result);
	}

}
